import { Injectable } from '@nestjs/common';
import { BookDto } from './dto/book.dto';
import { FileType } from "@/common/enums/file.enum";
import { ChapterParser } from './chapterParser';
import path from 'path';
import fs from 'fs-extra';
import { BookEntity } from './entities/book.entity';
import { ChaptersEntity } from './entities/chapters.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
@Injectable()
export class NovelService {

  private readonly basePath = path.join(process.cwd(), 'storage', 'files');
  constructor(
    @InjectRepository(BookEntity)
    private readonly bookRepository: Repository<BookEntity>,
    @InjectRepository(ChaptersEntity)
    private readonly chaptersRepository: Repository<ChaptersEntity>,
  ) { }

  async createBook(dto: BookDto, file: Express.Multer.File) {
    const book = this.bookRepository.create(dto);
    const chapters = new ChapterParser(file.path).parse();
    const bookEntity = await this.bookRepository.save(book);
    const id = bookEntity.id;
    const fileExt = path.extname(file.originalname);//获取文件扩展名
    const typeDir = path.join(this.basePath, FileType.Novel, id.toString());
    await fs.ensureDir(typeDir);

    // 批量创建章节实体
    const chapterEntities = chapters.map(item =>
      this.chaptersRepository.create({
        bookId: id,
        chapterNumber: +item.chapterNumber,
        title: item.title,
        fileName: item.chapterNumber + fileExt,
        filePath: path.join(typeDir, item.chapterNumber + fileExt),
      })
    );

    // 批量插入数据库
    await this.chaptersRepository.save(chapterEntities);

    // 批量写入文件
    const filePromises = chapters.map(item =>
      fs.writeFile(
        path.join(typeDir, item.chapterNumber + fileExt),
        item.content
      )
    );
    await Promise.all(filePromises);
    // 删除临时文件
    fs.remove(file.path);
    return book
  }

  async updateBook(id: number, bookDto: BookDto, file: Express.Multer.File) {

  }

  upload(file: Express.Multer.File) {
  }
}
